﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using BLL.BusinessClasses;

namespace WebSite.Egresado
{
    public partial class Vacantes : System.Web.UI.Page
    {
        #region Prueba
        /*
        protected static bool Flag = true;

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (this.MultiView_MakeQueryVacantes.ActiveViewIndex == this.MultiView_MakeQueryVacantes.Views.Count - 1 ||
                this.MultiView_MakeQueryVacantes.ActiveViewIndex == 0) Vacantes.Flag = !(Vacantes.Flag);

            if (Vacantes.Flag) this.MultiView_MakeQueryVacantes.ActiveViewIndex--;
            else this.MultiView_MakeQueryVacantes.ActiveViewIndex++;
        } 
        */
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Session["UsuarioDeSesion"] == null || !(this.Session["UsuarioDeSesion"] is UsuarioUniversitario))
            {
                this.Response.Redirect(@"~/General/Principal.aspx");
                return;
            }
            if (!(this.Page.IsPostBack))
            {
                this.DarBienvenida();
            }
        }

        // Click Event Handlers
        protected void Button_LogOff_Click(object sender, EventArgs e)
        {
            this.Session["UsuarioDeSesion"] = null;

            this.Response.Redirect(@"~/General/Principal.aspx");
        }

        protected void Button_OKViewSeleccionArea_Click(object sender, EventArgs e)
        {
            if (this.ListBox_AreasAcademicas.SelectedValue != String.Empty)
            {
                this.ListBox_Carreras.DataSource = from c in Carrera.GetCarrerasByAreaAcademicaID(Convert.ToInt32(this.ListBox_AreasAcademicas.SelectedValue))
                                                   select c;

                this.ListBox_Carreras.DataValueField = "ID";
                this.ListBox_Carreras.DataTextField = "Descripcion";

                this.ListBox_Carreras.DataBind();

                this.ViewState["LinqDataSource_Vacantes_WhereExpression"] = String.Empty;                
                this.ViewState["LinqDataSource_Vacantes_WhereExpression"] += " && Carrera.ID_AreaAcademica == @ID_AreaAcademica";                

                this.MultiView_MakeQueryVacantes.ActiveViewIndex++;
            }
            else 
            {
                this.Button_CancelViewSeleccionArea_Click(sender, e);
            }     
        }
        protected void Button_CancelViewSeleccionArea_Click(object sender, EventArgs e)
        {
            this.ListBox_Carreras.DataSourceID = this.LinqDataSource_Carreras.ID;

            this.ListBox_Carreras.DataValueField = "ID";
            this.ListBox_Carreras.DataTextField = "Descripcion";

            this.ListBox_Carreras.DataBind();

            this.MultiView_MakeQueryVacantes.ActiveViewIndex++;
        }

        protected void Button_OKViewSeleccionCarrera_Click(object sender, EventArgs e)
        {
            if (this.ListBox_AreasAcademicas.SelectedValue != String.Empty)
            {
                this.ListBox_Especialidades.DataSource = from p in Postgrado.GetPostgradosByAreaAcademicaID(Convert.ToInt32(this.ListBox_AreasAcademicas.SelectedValue))
                                                         select p;

                this.ListBox_Especialidades.DataValueField = "ID";
                this.ListBox_Especialidades.DataTextField = "Descripcion";

                this.ListBox_Especialidades.DataBind();

                this.MultiView_MakeQueryVacantes.ActiveViewIndex++;
            }
            else
            {
                this.ListBox_Especialidades.DataSourceID = this.LinqDataSource_Postgrados.ID;

                this.ListBox_Especialidades.DataValueField = "ID";
                this.ListBox_Especialidades.DataTextField = "Descripcion";

                this.ListBox_Especialidades.DataBind();

                this.MultiView_MakeQueryVacantes.ActiveViewIndex++;                
            } 

            if (this.ListBox_Carreras.SelectedValue != String.Empty)
            {
                // Añadiendo los parametros al query final
                this.ViewState["LinqDataSource_Vacantes_WhereExpression"] += " && ID_Carrera == @ID_Carrera";
            }
        }
        protected void Button_CancelViewSeleccionCarrera_Click(object sender, EventArgs e)
        {
            if (this.ListBox_AreasAcademicas.SelectedValue != String.Empty)
            {
                this.ListBox_Especialidades.DataSource = from p in Postgrado.GetPostgradosByAreaAcademicaID(Convert.ToInt32(this.ListBox_AreasAcademicas.SelectedValue))
                                                         select p;

                this.ListBox_Especialidades.DataValueField = "ID";
                this.ListBox_Especialidades.DataTextField = "Descripcion";

                this.ListBox_Especialidades.DataBind();

                this.MultiView_MakeQueryVacantes.ActiveViewIndex++;
            }
            else
            {
                this.ListBox_Especialidades.DataSourceID = this.LinqDataSource_Postgrados.ID;

                this.ListBox_Especialidades.DataValueField = "ID";
                this.ListBox_Especialidades.DataTextField = "Descripcion";

                this.ListBox_Especialidades.DataBind();

                this.MultiView_MakeQueryVacantes.ActiveViewIndex++;
            }            
        }

        protected void Button_OKViewSeleccionEspecialidad_Click(object sender, EventArgs e)
        {
#warning Esto no funciona!

            if (this.ListBox_Especialidades.SelectedValue != String.Empty)
                this.ViewState["SelectedEspecialidad"] = this.ListBox_Especialidades.SelectedValue;

            //Esto no funciona! La idea es la siguiente:

            //SELECT *
            //FROM [Vacantes] AS [t0]
            //WHERE EXISTS
            //(
            //    SELECT *
            //    FROM [Vacantes_Postgrados] AS [t1]
            //    WHERE ([t1].[ID_Postgrado] = @ID_Postgrado) AND ([t1].[ID_Vacante] = [t0].[ID])
            //)

            //from q in Vacantes
            //where (from i in Vacantes_Postgrados
            //       where i.ID_Postgrado == @ID_Postgrado && i.ID_Vacante == q.ID
            //       select i).Count() > 0
            //select q

            //donde @ID_Postgrado = this.ListBox_Especialidades.SelectedValue

            //Buscar la forma de que en this.ViewState["LinqDataSource_Vacantes_WhereExpression"] 
            //se pueda añadir el query anterior (el select que esta dentro del WHERE) como condicion

            //Este es un intento fallido:
            //this.ViewState["LinqDataSource_Vacantes_WhereExpression"] += 
            //    " && Vacantes_Postgrados.Contains(new Vacantes_Postgrado() { ID_Postgrado = @ID_Postgrado })";

            this.MultiView_MakeQueryVacantes.ActiveViewIndex++;
        }
        protected void Button_CancelViewSeleccionEspecialidad_Click(object sender, EventArgs e)
        {
            this.MultiView_MakeQueryVacantes.ActiveViewIndex++;
        }
        
        protected void Button_OKViewSeleccionPais_Click(object sender, EventArgs e)
        {
            if (this.ListBox_Pais.SelectedValue != String.Empty)
            {
                this.ViewState["LinqDataSource_Vacantes_WhereExpression"] += " && ID_Pais == @ID_Pais";                                
            }

            if (this.ViewState["LinqDataSource_Vacantes_WhereExpression"] != null)
            {
                this.LinqDataSource_Vacantes.Where += this.ViewState["LinqDataSource_Vacantes_WhereExpression"].ToString();

                this.LinqDataSource_Vacantes.WhereParameters.Add(new Parameter("ID_AreaAcademica", DbType.Int32, this.ListBox_AreasAcademicas.SelectedValue));
                this.LinqDataSource_Vacantes.WhereParameters.Add(new Parameter("ID_Carrera", DbType.Int32, this.ListBox_Carreras.SelectedValue));
                this.LinqDataSource_Vacantes.WhereParameters.Add(new Parameter("ID_Pais", DbType.Int32, this.ListBox_Pais.SelectedValue));
                this.LinqDataSource_Vacantes.WhereParameters.Add(new Parameter("ID_Postgrado", DbType.Int32, this.ListBox_Especialidades.SelectedValue));
            }

            //this.LinqDataSource_Vacantes.DataBind();
            //this.GridView_Vacantes.DataBind();

            this.MultiView_MakeQueryVacantes.ActiveViewIndex++;                       
        }
        protected void Button_CancelViewSeleccionPais_Click(object sender, EventArgs e)
        {
            if (this.ViewState["LinqDataSource_Vacantes_WhereExpression"] != null)
            {
                this.LinqDataSource_Vacantes.Where += this.ViewState["LinqDataSource_Vacantes_WhereExpression"].ToString();

                this.LinqDataSource_Vacantes.WhereParameters.Add(new Parameter("ID_AreaAcademica", DbType.Int32, this.ListBox_AreasAcademicas.SelectedValue));
                this.LinqDataSource_Vacantes.WhereParameters.Add(new Parameter("ID_Carrera", DbType.Int32, this.ListBox_Carreras.SelectedValue));
                this.LinqDataSource_Vacantes.WhereParameters.Add(new Parameter("ID_Pais", DbType.Int32, this.ListBox_Pais.SelectedValue));
                this.LinqDataSource_Vacantes.WhereParameters.Add(new Parameter("ID_Postgrado", DbType.Int32, this.ListBox_Especialidades.SelectedValue));
            }

            //this.LinqDataSource_Vacantes.DataBind();
            //this.GridView_Vacantes.DataBind();

            this.MultiView_MakeQueryVacantes.ActiveViewIndex++;    
        }

        protected void LinqDataSource_Vacantes_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            if (this.ViewState["SelectedEspecialidad"] != null)
            {
                BLL.DataContextClasses.DataClassesDataContext DB = new BLL.DataContextClasses.DataClassesDataContext();
                var ResultQuery = from v in DB.Vacantes
                                  select v;

                if (this.LinqDataSource_Vacantes.WhereParameters.Contains(new Parameter("ID_AreaAcademica", DbType.Int32, this.ListBox_AreasAcademicas.SelectedValue)))
                {
                    ResultQuery = from q in ResultQuery
                                  where q.Carrera.ID_AreaAcademica == Convert.ToInt32(this.ListBox_AreasAcademicas.SelectedValue) 
                                  select q;
                }
                if (this.LinqDataSource_Vacantes.WhereParameters.Contains(new Parameter("ID_Carrera", DbType.Int32, this.ListBox_Carreras.SelectedValue))) 
                {
                    ResultQuery = from q in ResultQuery
                                  where q.Carrera.ID == Convert.ToInt32(this.ListBox_Carreras.SelectedValue)
                                  select q;
                }
                if (this.LinqDataSource_Vacantes.WhereParameters.Contains(new Parameter("ID_Pais", DbType.Int32, this.ListBox_Pais.SelectedValue)))
                {
                    ResultQuery = from q in ResultQuery
                                  where q.ID_Pais == Convert.ToInt32(this.ListBox_Pais.SelectedValue)
                                  select q;
                }

                e.Result = from q in ResultQuery
                           where (from i in q.Vacantes_Postgrados
                                  where i.ID_Postgrado == Convert.ToInt32(this.ListBox_Especialidades.SelectedValue)
                                  select i).Count() > 0
                           select q;
            }
        }


        protected void Button_AplicarAVacante_Click(object sender, EventArgs e)
        {
            try
            {
                ((UsuarioUniversitario)this.Session["UsuarioDeSesion"]).AplicarAVacante(Convert.ToInt32(this.GridView_Vacantes.SelectedValue), this.TextBox_Comentarios.Text.Trim());
                this.Label_MensajeNotificacionVacanteAplicada.Text = "La aplicacion ha sido realizada";
                this.Label_MensajeNotificacionVacanteAplicada.Visible = true;
            }
            catch (Exception)
            {
                this.Label_MensajeNotificacionVacanteAplicada.Text = "No ha podido aplicar a esta vacante. Verifique si ya tiene una aplicacion a esta vacante o intente nuevamente en unos minutos";
                this.Label_MensajeNotificacionVacanteAplicada.Visible = true;
            }
        }
        
        // Helper Methods
        protected void GridView_Vacantes_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.GridView_Vacantes.SelectedIndex != -1)
            {
                this.Panel_DatosVacante.Visible = true;
                this.Panel_Aplicar.Visible = true;
                this.GridView_DatosVacante.Focus();
            }
        }
        protected void GridView_Vacantes_PageIndexChanged(object sender, EventArgs e)
        {
            this.GridView_Vacantes.SelectedIndex = -1;
            this.Panel_DatosVacante.Visible = false;
            this.Panel_Aplicar.Visible = false;
        }

        protected void GridView_DatosVacante_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (((string)DataBinder.Eval(e.Row.DataItem, "Empresa.Foto")) != null)
                {
                    ((Image)e.Row.FindControl("Image_LogoEmpresa")).ImageUrl = ((string)DataBinder.Eval(e.Row.DataItem, "Empresa.Foto"));
                }
                else
                {
                    ((Image)e.Row.FindControl("Image_LogoEmpresa")).ImageUrl = "~\\Pictures\\CompanyPictures\\DefaultCompanyPic.png";
                }

                if (((ListBox)e.Row.FindControl("ListBox_DatosVacanteHabilidades")).Items.Count == 0)
                {
                    ((ListBox)e.Row.FindControl("ListBox_DatosVacanteHabilidades")).Visible = false;
                    ((Label)e.Row.FindControl("Label_DatosVacanteNoHabilidades")).Visible = true;
                }
                if (((ListBox)e.Row.FindControl("ListBox_DatosVacanteEspecialidades")).Items.Count == 0)
                {
                    ((ListBox)e.Row.FindControl("ListBox_DatosVacanteEspecialidades")).Visible = false;
                    ((Label)e.Row.FindControl("Label_DatosVacanteNoPostgrados")).Visible = true;
                }
            }
        }
        private void DarBienvenida()
        {
            ((Label)(this.Master.FindControl("Label_Bienvenida"))).Text = "Bienvenido <u>" +
                                                                          ((UsuarioUniversitario)this.Session["UsuarioDeSesion"]).PrimerNombre + " " +
                                                                          ((UsuarioUniversitario)this.Session["UsuarioDeSesion"]).PrimerApellido + "</u>";
        }        

        // Page Expressions Methods
        protected object EvaluateIfPuestoEqualsNull()
        {
            return (Eval("Puesto") == null) ? "<span class=\"LetraRoja\">No Especificado</span>" : Eval("Puesto");
        }
        protected object ContarAplicacionesActivas()
        {
            return new Vacante(Convert.ToInt32(Eval("ID"))).Aplicaciones.Count(a => a.SiActiva);
        }

        

                  
    }
}
